<template>
  <UploadExcel :on-success="upload" />
</template>

<script>
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    async upload(data) {
      console.log(data)

      const newData = data.results.map(user => {
        console.log(user)
        // 现在的 user 都是中文 key
        // 希望转换成一个英文 key 的对象
        return this.zh2en(user)
      })

      console.log(newData)

      await importEmployees(newData)

      // 返回到前一页
      this.$message.success('导入成功')
      this.$router.back()
    },
    zh2en(user) {
      const newUser = {}
      // 准备字典
      const dict = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      for (const key in user) {
        // 中文key = key
        // 英文key = dict[key]
        // 源数据 = user[key]
        // console.log(key)
        const enKey = dict[key]
        // console.log(enKey)
        // console.log(user[key])
        let value = user[key]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = new Date(this.formatDate(value, '/'))
        }
        newUser[enKey] = value
      }
      // 翻译逻辑
      return newUser
    },
    // excel 专用
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
